<template>
  <div class="combined-charts-container">
    <div ref="lineChart" class="chart-card"></div>
    <div ref="barChart" class="chart-card"></div>
  </div>
</template>
  
  <script>
  import * as echarts from 'echarts'
  export default {
    props: {
      originData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        lineChart: null,
        barChart: null,
        colorList: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272'] // 6种颜色
      }
    },
    computed: {
      // 处理折线图数据
      lineSeriesData() {
        const series = []
        for (let questId = 1; questId <= 6; questId++) {
          series.push({
            name: `指标 ${questId}`,
            type: 'line',
            data: this.getTimeSeries(questId),
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: { width: 2 },
            areaStyle: { opacity: 0.1 }
          })
        }
        return series
      },
  
      // 处理柱状图数据（各指标总平均分）
      barChartData() {
        const averages = []
        for (let questId = 1; questId <= 6; questId++) {
          const scores = this.originData
            .filter(d => d.questId == questId)
            .map(d => d.evaScore)
          averages.push({
            name: `指标 ${questId}`,
            value: (scores.reduce((a, b) => a + b, 0) / scores.length).toFixed(2) || 0
          })
        }
        return averages
      },
  
      // 获取所有时间点（X轴）
      timeAxis() {
        const times = [...new Set(this.originData.map(d => 
          new Date(d.evaTime).toISOString().split('T')[0]
        ))].sort()
        return times
      }
    },
    methods: {
      // 生成时间序列数据
      getTimeSeries(questId) {
        const timeMap = new Map()
        this.originData
          .filter(d => d.questId == questId)
          .forEach(d => {
            const time = new Date(d.evaTime).toISOString().split('T')[0]
            if (!timeMap.has(time)) {
              timeMap.set(time, [])
            }
            timeMap.get(time).push(d.evaScore)
          })
  
        return this.timeAxis.map(time => {
          const scores = timeMap.get(time) || []
          return scores.length > 0 
            ? (scores.reduce((a, b) => a + b) / scores.length).toFixed(2)
            : null
        })
      },
  
      // 初始化折线图
      initLineChart() {
        this.lineChart = echarts.init(this.$refs.lineChart)
        const option = {
          title: { 
            text: '评教指标趋势分析',
            left: 'center',
            textStyle: {
              color: '#2c3e50',
              fontSize: 18,
              fontWeight: '600'
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(50,50,50,0.95)',
            borderWidth: 0,
            textStyle: { color: '#fff' },
            formatter: params => {
              const date = new Date(params[0].name)
              return `<div class="chart-tooltip">
                <div class="date">${date.toLocaleDateString('zh-CN', { 
                  year: 'numeric', 
                  month: '2-digit', 
                  day: '2-digit'
                })}</div>
                ${params.map(p => `
                  <div class="item">
                    <span class="dot" style="background:${p.color}"></span>
                    ${p.seriesName}: <strong>${p.value || '无数据'}</strong>
                  </div>
                `).join('')}
              </div>`
            }
          },
          legend: {
            top: 35,
            icon: 'circle',
            itemWidth: 8,
            textStyle: { color: '#666' },
            data: this.lineSeriesData.map(d => d.name)
          },
          grid: {
            top: 80,
            left: 50,
            right: 30,
            bottom: 30
          },
          xAxis: {
            type: 'category',
            axisLine: { lineStyle: { color: '#ddd' } },
            axisLabel: {
              color: '#666',
              formatter: value => {
                const date = new Date(value)
                return `${date.getMonth()+1}/${date.getDate()}`
              }
            },
            data: this.timeAxis
          },
          yAxis: {
            type: 'value',
            min: 0,
            max: 25,
            splitLine: { lineStyle: { type: 'dashed' } },
            axisLine: { show: false },
            axisLabel: { color: '#666' }
          },
          series: this.lineSeriesData.map(series => ({
            ...series,
            lineStyle: { width: 3 },
            symbolSize: 8,
            areaStyle: {
              opacity: 0.15,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255,255,255,0)' },
                { offset: 1, color: 'rgba(255,255,255,0)' }
              ])
            }
          })),
          color: this.colorList
        }
        this.lineChart.setOption(option)
      },
  
      // 初始化柱状图
      initBarChart() {
        this.barChart = echarts.init(this.$refs.barChart)
        const option = {
          title: { 
            text: '各指标平均分对比',
            left: 'center',
            textStyle: {
              color: '#2c3e50',
              fontSize: 18,
              fontWeight: '600'
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(50,50,50,0.95)',
            borderWidth: 0,
            textStyle: { color: '#fff' },
            formatter: params => {
              return `<div class="chart-tooltip">
                <div class="item">
                  <span class="dot" style="background:${params[0].color}"></span>
                  ${params[0].name}: <strong>${params[0].value}</strong>
                </div>
              </div>`
            }
          },
          grid: {
            top: 60,
            left: 50,
            right: 30,
            bottom: 30
          },
          xAxis: {
            type: 'category',
            axisLine: { lineStyle: { color: '#ddd' } },
            axisLabel: {
              color: '#666',
              interval: 0,
              rotate: 30
            },
            data: this.barChartData.map(d => d.name)
          },
          yAxis: {
            type: 'value',
            min: 0,
            max: 25,
            splitLine: { lineStyle: { type: 'dashed' } },
            axisLine: { show: false },
            axisLabel: { color: '#666' }
          },
          series: [{
            name: '平均分',
            type: 'bar',
            data: this.barChartData,
            itemStyle: {
              color: params => this.colorList[params.dataIndex],
              borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0,0,0,0.2)'
              }
            },
            barWidth: '60%'
          }]
        }
        this.barChart.setOption(option)
      },
  
      // 更新图表
      updateCharts() {
        this.lineChart.setOption({
          xAxis: { data: this.timeAxis },
          series: this.lineSeriesData
        })
        this.barChart.setOption({
          series: [{
            data: this.barChartData
          }]
        })
      }
    },
    watch: {
      originData: {
        handler() {
          this.$nextTick(() => this.updateCharts())
        },
        deep: true
      }
    },
    mounted() {
      this.initLineChart()
      this.initBarChart()
      
      // 响应式调整
      const resizeHandler = () => {
        this.lineChart.resize()
        this.barChart.resize()
      }
      window.addEventListener('resize', resizeHandler)
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler)
        this.lineChart.dispose()
        this.barChart.dispose()
      })
    }
  }
  </script>
  
<style lang="scss" scoped>
.combined-charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
  gap: 24px;
  padding: 20px;

  .chart-card {
    height: 500px; /* 新增高度设置 */
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transition: transform 0.3s ease, box-shadow 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(0,0,0,0.12);
    }
  }
}

@media (max-width: 768px) {
  .combined-charts-container {
    grid-template-columns: 1fr;
    padding: 10px;
    
    .chart-card {
      padding: 15px;
    }
  }
}
</style>